﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;

namespace scavenger
{
    public class Utils
    {
        public static string GetHash(string filename,CryptoAlgoEnum cryptoAlgo)
        {
            HashAlgorithm algo = null;
            StringBuilder sb = new StringBuilder();

            switch (cryptoAlgo)
            { 
                case CryptoAlgoEnum.MD5:
                    algo = new MD5CryptoServiceProvider();
                    break;
                case CryptoAlgoEnum.SHA256:
                    algo = new SHA256CryptoServiceProvider();
                    break;
                case CryptoAlgoEnum.SHA512:
                    algo = new SHA512CryptoServiceProvider();
                    break;
            }


            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) 
            {
                foreach (Byte b in algo.ComputeHash(fs))
                    sb.Append(b.ToString("x2").ToLower());
            }

            return sb.ToString();
        }

        public static void SerializeToBinary(object o,Stream fs)
        {
            BinaryFormatter binfmt = new BinaryFormatter();
            binfmt.Serialize(fs, o);
        }

        public static object DeserializeFromBinary(Stream fs)
        {
            BinaryFormatter binfmt = new BinaryFormatter();
            return binfmt.Deserialize(fs);
        }

        public static void WriteLog(string message)
        {
            WriteLog(message, true);
        }

        public static void WriteLog(string message, bool maintenance)
        {
            try
            {
                System.Diagnostics.StackFrame f = new System.Diagnostics.StackFrame(2);
                string methodname = f.GetMethod().Name;
                string fname = AppDomain.CurrentDomain.BaseDirectory + "scavenger.log";
                StreamWriter sw = new StreamWriter(fname, true);
                //message=String.Format ("{0:dd-MMM-yyyy HH:mm:ss}",DateTime.Now) + message;
                sw.WriteLine(string.Format("{0:dd-MMM-yyyy HH:mm:ss}", DateTime.Now) + ": " + methodname + ": " + message);
                sw.Close();

                if (maintenance)
                {
                    FileInfo fi = new FileInfo(fname);
                    if (fi.Length > 1000000000)
                    {
                        File.Delete(fname); //TODO: Clear initial n lines instead of deleting the entire file
                    }
                    fi = null;
                }
            }
            catch
            {
            }
        }
    }
}
